<div class="layuimini-container layuimini-page-anim">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <div class="layui-input-inline">
                                <input type="text" name="key" autocomplete="off" class="layui-input" placeholder="请输入学号或姓名查询">
                            </div>
                        </div>
                        <div class="layui-inline">
                          <label class="layui-form-label">年级</label>
                          <div class="layui-input-inline">
                              <select name="grade" id="grade">
                                
                              </select>
                          </div>
                      </div>
                      
                      <div class="layui-inline">
                        <label class="layui-form-label">班级</label>
                        <div class="layui-input-inline" >
                            <select name="class"  id="class" lay-search=""> 
                                
                            </select>
                        </div>
                    </div>
                        <div class="layui-inline">
                            <button class="layui-btn layuiadmin-btn-list" lay-submit lay-filter="search-submit">
                                <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>
<!--        toolbarDemo就是头部工具栏的id-->
        <script type="text/html" id="Stubar">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加学生 </button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="deletePart"> 批量删除 </button>
                <button class="layui-btn  layui-btn-sm " lay-event="exportData" style="background: #27ae60"> 导出全部 </button>
            </div>
        </script>

        <table class="layui-hide" id="stuTableId" lay-filter="stuTableFilter"></table>
        <script type="text/html" id="StubarEach">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>
    </div>
</div>

<script>
    layui.use(['form', 'table','miniPage','element','upload','store','opTable','axios'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            upload = layui.upload,
            store = layui.store,
            opTable = layui.opTable,
            axios = layui.axios,
            miniPage = layui.miniPage;

        form.render() //处理有时候下拉框会消失
        opTable.render({
            elem: '#stuTableId'
            , id: 'stuTableId'
            , method:'post'
            , url: '/student/list'
            , defaultToolbar: ['filter', 'print'] //头部工具栏
            , toolbar: '#Stubar'
            , page: true
            , cols: [[
                {type: "checkbox", width: 50}
                ,{type: "numbers", title: 'ID',width: 50}
                // ,{field: 'id', title: 'ID', sort: true}
                ,{field: 'sno', title: '学号', sort: true}
                , {field: 'username', title: '用户名'}
                , {field: 'name', title: '姓名'}
                ,{
                    field: 'sex', title: '性别', templet: function (d) {
                        if (d.sex == 1) return '<div>男</div>';
                        else if (d.sex == 0) return '<div>女</div>';
                    }
                }
                , {field: 'gradeName', title: '年级'}
                , {field: 'className', title: '班级'}
                , {title: '操作', toolbar: '#StubarEach', width: 150, align: "center"}
            ]]

            //  展开的列配置
            , openCols: [
                {field: 'idcard', title: '身份证'}
                ,{field: 'phone', title: '联系方式'}
            ]
            , onEdit: function (data) {
                layer.msg(JSON.stringify(data));
            }, openType: 0
            ,limits: [5, 10, 15, 20, 25, 50, 100]
            ,limit: 10
            ,parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data.count, //解析数据长度
                    "data": res.data.stus //解析数据列表
                };
            }
        });

        form.on('submit(search-submit)',function (data) {
          
            table.reload('stuTableId',{
                where:{
                    "key":data.field.key,
                    "gradeId":data.field.grade,
                    "classId":data.field.class
                }
            });
            return false;
        });

        //加载出年级
        axios({
            method:"get",
            url:"grade/list",
            async:false
        }).then(response=>{
            response_data = response.data.grades
            let options = '<option value="">请选择年级</option>';
            for (let obj of response_data) {
                options += '<option value="' + obj.id + '">' + obj.name + '</option>'
            }
            $('#grade').append(options);
            form.render('select');//处理动态赋值
        })

        //加载出班级
        axios({
            method:"get",
            url:"org/getClasses",
            async:false
        }).then(response=>{
            response_data = response.data.classes
            let options = '<option value="">请选择班级</option>';
            for (let obj of response_data) {
                options += '<option value="' + obj.id + '">' + obj.name + '</option>'
            }
            $('#class').append(options);
            form.render('select');
        })

        /**
         * toolbar(表格头部工具栏)
         * tabel.on 事件监听
         * 监听表格的头部工具栏
         */
        table.on('toolbar(stuTableFilter)', function (obj) {
            switch (obj.event) {
                case "add":{
                    var content = miniPage.getHrefContent('student/add.html');
                    var openWH = miniPage.getOpenWidthHeight();

                    var index = layer.open({
                        title: '添加用户',
                        type: 1,//页面层
                        shade: 0.2,
                        maxmin:false,
                        shadeClose: true,
                        area: [openWH[0] + 'px', openWH[1] + 'px'],
                        offset: [openWH[2] + 'px', openWH[3] + 'px'],
                        content: content,
                    });
                    $(window).on("resize", function () {
                        layer.full(index);
                    });
                    break;
                }
                case "deletePart":{
                    var data = table.checkStatus('stuTableId').data
                    console.log(data)
                    if(data.length==0){
                        layer.msg("请至少选择一条数据删除",{
                          icon:5,
                          time:2000,
                          anim:6
                        })
                    }else{
                        layer.confirm('真的要删除这些学生数据吗？', function (index) {
                            let userIds = data.map(item=>item.userId)
                            userIdsStr = userIds.join(",")
                            let stuIds = data.map(item=>item.id)
                            stuIdsStr = stuIds.join(",")
                            console.log(userIdsStr)
                            axios.delete("student/deletePart/"+userIdsStr+"/"+stuIdsStr)
                                .then(data=>{
                                    layer.msg(data.message,{
                                      icon:6,
                                      time:2000,
                                    },function () {
                                        table.reload("stuTableId")
                                    })
                                }).catch(error=>{
                                layer.msg("请求错误",{
                                  icon:5,
                                  time:2000,
                                  anim:6
                                })
                            });
                        });
                    }
                    break;
                }
                case "exportData":{
                    layer.confirm('确定导出所有学生信息吗？', {
                        btn: ['确定', '取消']
                    }, function(index){
                        axios({
                            method: 'get',
                            url:'/student/exportAll',
                            responseType: 'blob',   // 重要， 限制返回的数据结构为blob格式，方便前端做转换
                        }).then(data=>{
                            const link = document.createElement('a')
                            const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
                            link.style.display = 'none'
                            link.href = URL.createObjectURL(blob)
                            link.setAttribute('download','学生信息.xlsx')
                            document.body.appendChild(link)
                            link.click()
                            document.body.removeChild(link)
                        })
                        layer.close(index);
                    }, function(index){
                        //按钮【按钮二】的回调
                    });
                    break;
                }
            }
        });

        table.on('tool(stuTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {

                var content = miniPage.getHrefContent('student/edit.html');
                var openWH = miniPage.getOpenWidthHeight();

                var index = layer.open({
                    title: '编辑学生',
                    type: 1,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: [openWH[0] + 'px', openWH[1] + 'px'],
                    offset: [openWH[2] + 'px', openWH[3] + 'px'],
                    content: content,
                });
                //加载出年级
                axios({
                    method:"get",
                    url:"grade/list",
                    async:false
                }).then(response=>{
                    //处理select 的加载问题
                    // 一种在前一个前面
                    // 第二种就是传入一个临时值
                    //      <option value="' + obj.id + '" selected>'
                    response_data = response.data.grades
                    let options = '<option value="">请选择年级</option>';
                    for (let obj of response_data) {
                        options += '<option value="' + obj.id + '">' + obj.name + '</option>'
                    }
                    $('#gradeId').append(options);
                    form.render('select');//处理动态赋值
                    

                    form.val("edit-stu", {
                        "id":data.id,
                        "userId":data.userId,
                        "sno":data.sno,
                        "username":data.username,
                        "name":data.name,
                        "sex":data.sex,
                        //年级
                        "gradeId":data.gradeId,
                        //班级
                        "className":data.className,
                        "classId":data.classId,
                        "remark":data.remark,
                        "idcard":data.idcard,
                        "phone":data.phone,
                    });
                })

                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('真的要删除该学生信息吗？', function (index) {
                    axios({
                        method:'delete',
                        url:'/student/deleteOne/'+data.userId+"/"+data.id
                    }).then(data=>{
                        layer.msg(data.message,{
                          icon:6,
                          time:2000
                        },function () {
                            table.reload("stuTableId")
                        })
                    }).catch(error=>{
                        layer.msg("请求错误",{
                          icon:5,
                          time:2000,
                          anim:6
                        })
                    });
                    layer.close(index);
                });
            }
        });
    });
</script>